#include "abr.h"

nodi *addabr(nodi *abr, nodi* tmp)
{
    nodi *fgtmp = abr->fg;
    nodi *fdtmp = abr->fd;
  if(compclef(abr->clef, tmp->clef)== -1)
    {
      if(abr->fg!=NULL)
	{
	  if(compclef(fgtmp->clef, tmp->clef)==-1)
	    {
	      abr->fg = addabr(abr->fg,tmp);
	      return abr;
	    }
	}
      else if(abr->fd!=NULL)
	{
	  if(compclef(fdtmp->clef,tmp->clef))
	    {
	      abr->fd = addabr(abr->fd,tmp);
	      return abr;
	    }
	}
      else
	{
	  return tmp;
	}
    }
  else
    {
      if(abr->fg!=NULL)
	{
	  if(compclef(fgtmp->clef, tmp->clef)==-1)
	    {
	      abr->fg = addabr(abr->fg,tmp);
	      return abr;
	    }
	}
      else if(abr->fd!=NULL)
	{
	  if(compclef(fdtmp->clef,tmp->clef))
	    {
	      abr->fd = addabr(abr->fd,tmp);
	      return abr;
	    }
	}
      else
	{
	  return tmp;
	}
    }
}

nodi *createnodi(nodi *abr,char *key, void *value,char *type)
{
  nodi *tmp = malloc( sizeof(nodi));
  tmp->clef = malloc(20*sizeof(char));
  tmp->value = malloc(100*sizeof(char));
  tmp->type = malloc(7*sizeof(char));
  tmp->clef = monstrcat(tmp->clef, key);
  tmp->type = monstrcat(tmp->type, type);
  if(value != NULL)
    tmp->value = monstrcat(tmp->clef, value);

  return(addabr(abr, tmp));
}

int compclef(char *a, char *b)
{
  int i = 0;
  while((a[i] != '\0') && (b[i] != '\0') && (a[i] == b[i])){i++;}


  if(a[i] == b[i])
    return 0;
  else if (a[i] < b[i])
    return 1;
  else
    return -1;
}


nodi *recherche(nodi *abr, char *key)
{
  if(compclef(key, abr->clef) == 0)
    return abr;
  else if(compclef(key, abr->clef) == 1)
    return (recherche(abr->fg, key));
  else if(compclef(key,abr->clef) == -1)
    return(recherche(abr->fd, key));
  else
    {
      nodi *tmp = malloc(sizeof(nodi));
      tmp->clef = malloc(20*sizeof(char));
      tmp->clef = monstrcat(tmp->clef, "ERROR !");
      return tmp;
    }
}

void destroy(nodi *abr)
{
  nodi *tmp = malloc(sizeof(nodi));
  if(abr->fg != NULL)
    destroy(abr->fg);
  else if (abr->fd != NULL)
    destroy(abr->fd);
  free(abr);
}

int returnint(nodi *abr)
{
  if(!strcmp(abr->type, "ent"))
    return((int)abr->value);
  return -424242;
}

char returnchar(nodi *abr)
{
  if(!strcmp(abr->type,"car"))
    return((char)abr->value);
  return '\0';
}

char *returnstr(nodi *abr)
{
  if(abr->type == "care")
    return((char*)abr->value);
  return "ERROR";
}

float returnfloat(nodi *abr)
{
  if(!strcmp(abr->type,"flott"))
    return((float)abr->value);
  return -.4242;
}








